<template>
	<codemirror :value="codeValue" :options="options" class="common-code"></codemirror>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { codemirror } from 'vue-codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/scroll/simplescrollbars.css';
import 'codemirror/addon/scroll/simplescrollbars';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/markdown/markdown';
import 'codemirror/mode/http/http';
import 'codemirror/addon/runmode/colorize.js';
@Component({
  name: 'codePreview',
  components: {
    codemirror
  }
})
export default class extends Vue {
  @Prop({ default: '' }) public viewFileUrl!: string;
  private mode: string = 'javascript';
  private codeValue: string = '';
  private get options () {
    return {
      value: '',
      tabSize: 2,
      mode: this.mode,
      matchBrackets: true,
      lineNumbers: false,
      lineWrapping: 'wrap',
      line: true,
      addModeClass: true,
      forceBreak: true,
      readOnly: true,
      showCursorWhenSelecting: true,
      theme: 'default'
    };
  }

  private created () {
    this.urlToBlob()
  }

  private urlToBlob () {
    fetch(this.viewFileUrl, {
      method: 'GET'
    }).then(res => {
      return res.blob();
    }).then(blob => {
      // 获取mode类型
      this.mode = blob.type;
      // markdown格式返回
      if (this.mode === 'application/octet-stream') {
        this.mode = 'markdown';
      }
      // 读取文件流
      const reader = new FileReader()
      reader.onload = () => {
        this.codeValue = reader.result + '';
        // 默认使用utf-8转码 如果出现乱码的情况 使用GB2312转码
        if (this.codeValue.includes('�')) {
          reader.readAsText(blob, 'GB2312');
          reader.onload = () => {
            this.codeValue = reader.result + '';
          };
        }
      }
      reader.readAsText(blob);
    })
  }
}
</script>

<style lang="stylus" scoped>
.common-code {
	max-width calc(100vw - 520px)
	max-height calc(100vh - 228px)
	overflow auto
	border-radius 4px
	/deep/.CodeMirror {
		background rgba(0, 0, 0, 0.03) !important
		text-align: left;
		position relative
		overflow hidden
		background white
		padding 5px 5px 5px
		position relative
		font-family PingFang SC
		cursor text
		border-radius 4px
		padding-right 32px
		height 100%
		color #000
		font-size 14px
		line-height 20px
	}
}
.custome-code {
	/deep/.CodeMirror {
		height 100%
	}
}
</style>
